import { makeAutoObservable, observable } from 'mobx';
import * as api from './api';
import { t } from '@lingui/macro';
import moment from 'moment';
import { Message } from '@alifd/next';
import { MAGIC_NUMBER } from './definitions_set';

export default class ScShareStore {
  _args = {
    search: {},
    pg: {
      page: 0,
      sort: [],
      size: 10,
    },
  };
  total = 0;
  data = [];
  loading = false;
  operationInfo = {};
  _action = '0';

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  get api() {
    return api;
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._args);
    search.history = Number(this._action);
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield api.count({ search });
      const prices = yield api.search({ search, pg });
      this.data = prices;
    } finally {
      this.loading = false;
    }
  }

  * _reload() {
    yield this.query();
  }

  async update(price) {
    try {
      const { enabled } = price;
      await api.update({ ...price, enabled: !enabled });
      await this.query();
      Message.success({ content: t`更新成功`, duration: 7000 });
    } catch (error) {
      Message.error({ content: t`更新失败`, duration: 7000 });
      throw error;
    }
  }

  * create(data, type) {
    const { routePriceId, shiftType, day, state } = data;
    let params = {
      routePriceId,
      shiftType,
      day,
      state,
      type: 2,
    };
    if (Number(shiftType) === 1) {
      const { flowShifts } = data;
      const { firstTime, lastTime, interval, description = '' } = flowShifts;
      params = {
        ...params,
        flowShifts: {
          firstTime: moment(firstTime?.$d).format('HH:mm'),
          lastTime: moment(lastTime?.$d).format('HH:mm'),
          interval,
          description,
        },
      };
    } else {
      const { fixedShifts, list } = data;
      const { description = '' } = fixedShifts || {};
      params = {
        ...params,
        fixedShifts: {
          description,
          scheduleItems: list.map((item) => ({
            date: item.date,
            carpoolUnitPrice: {
              RMB: item.carpoolUnitPrice,
              HKD: item.carpoolUnitPrice,
              MOP: item.carpoolUnitPrice,
            },
            startCarpoolCount: item.startCarpoolCount,
          })),
        },
      };
    }
    if (type === '1') {
      params = {
        ...params,
        realTimeUpdate: true,
      };
    } else {
      params = {
        ...params,
        realTimeUpdate: false,
      };
    }
    yield api.shiftCreate(params);
    yield this.query();
  }

  * remove(id) {
    yield api.shiftDelete(id);
    yield this.query();
  }

  * updateState(price) {
    // eslint-disable-next-line no-param-reassign
    price.state = price.state === '0' ? '1' : '0';
    yield api.update(price);
    yield this.query();
  }

  * getPriceInfo(id) {
    const res = yield api.getPriceInfo(id);
    return observable(res);
  }

  * existRsOrder(args) {
    return yield api.existRsOrder(args);
  }

  * updateShiftTime(args, data) {
    yield api.updateShiftTime(args, data);
    yield this.query();
  }

  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  get action() {
    return this._action;
  }

  set action(value) {
    this._action = value;
    this._args.pg.page = 0;
    this.query({ page: 0 });
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
    // _.mergeWith(this._args.pg, pg, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }

  /**
   * @func 判断是否创建拼车线路
   * @desc
   * @param {string} lineId 线路id
   * @return {object} {isCreate:Boolean 是否创建,shiftInfo:object}
   */
  async isCreateRsShift(lineId) {
    const { SHIFT_TYPE } = MAGIC_NUMBER;
    const param = {
      type: SHIFT_TYPE.CARPOOLING,
    };
    const res = await api.isHasShift(lineId, param);
    const { scheduleItems = [] } = res?.fixedShifts || {};
    return {
      isCreate: scheduleItems?.length <= 0,
      shiftInfo: res,
    };
  }

  /**
   * @func 更新拼车线路
   * @desc
   * @param {}
   * @return {}
   */
  async updateRsShift(data, type) {
    const { SHIFT_TYPE, CARPOOLING_SHIFT_TYPE } = MAGIC_NUMBER;
    const { SHIFT_INFO: shiftInfo, list, ...params } = data;
    const mapList = list.map((item) => ({
      ...item,
      carpoolUnitPrice: {
        RMB: Number(item.carpoolUnitPrice),
        HKD: Number(item.carpoolUnitPrice),
        MOP: Number(item.carpoolUnitPrice),
      },
    }));
    const { shiftType } = params || {};
    const isFlowShift = String(shiftType) === CARPOOLING_SHIFT_TYPE.FLOW;
    const { fixedShifts } = shiftInfo || {};
    const curFixedShifts = _.cloneDeep(fixedShifts);
    _.assign(curFixedShifts, { scheduleItems: mapList });
    const updateData = _.cloneDeep(params);
    _.assign(updateData, {
      id: shiftInfo?.id,
      realTimeUpdate: type === '1',
      fixedShifts: isFlowShift ? null : curFixedShifts,
      type: String(SHIFT_TYPE.CARPOOLING),
    });
    await api.updateRsShift(toJS(updateData));
    await this.query();
  }
}

